import SwiftUI

// AI控制视图
struct AIControlView: View {
    @EnvironmentObject var tcpCarService: TCPCarService
    @EnvironmentObject var connectionSettings: ConnectionSettings
    
    @StateObject private var aiService = AIService()
    @StateObject private var commandExecutor: AICommandExecutor
    
    @State private var naturalLanguageCommand = ""
    @State private var showSuggestions = false
    @State private var showErrorAlert = false
    @State private var errorMessage = ""
    @State private var showSuccessAlert = false
    @State private var successMessage = ""
    @State private var isProcessing = false
    
    // 常用命令建议 - 适配连续速度控制和舞蹈动作
    private let commonCommands = [
        // 基础动作
        "走正方形",
        "走圆形", 
        "前进10米",
        "左转90度",
        "右转90度",
        "后退5米",
        "停止",
        "绕障碍物",
        
        // 舞蹈动作
        "跳一段简单的舞",
        "快速摆动舞",
        "旋转舞",
        "8字舞",
        "摇摆舞",
        "节拍舞",
        
        // 复杂动作
        "走S形路线",
        "画一个心形",
        "螺旋前进",
        "Z字形移动",
        "花样表演",
        "模拟醉酒行走",
 
        // 新增音乐相关
        "音乐舞蹈",
        "播放音乐",
        "节拍跳舞",
        "带音乐跳舞"
    ]
    
    init() {
        // 初始化命令执行器
        let executor = AICommandExecutor()
        self._commandExecutor = StateObject(wrappedValue: executor)
    }
    
    // 在视图出现时设置服务引用
    private func setupServices() {
        // 设置TCP服务引用
        commandExecutor.setTCPCarService(tcpCarService)
        
        // 如果有CarControlService，也可以设置
        // 这里暂时只使用TCPCarService
    }
    
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                // 标题
                VStack(alignment: .leading, spacing: 8) {
                    Text("AI智能控制")
                        .font(.title2)
                        .fontWeight(.bold)
                    
                    Text("用自然语言控制小车，让AI理解您的意图并执行相应动作")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding(.horizontal)
                
                // 连接状态
                ConnectionStatusView()
                    .padding(.horizontal)
                
                // 自然语言输入区域
                VStack(alignment: .leading, spacing: 12) {
                    Text("输入指令")
                        .font(.headline)
                    
                    VStack(spacing: 8) {
                        TextField("例如：走正方形、前进10米、左转90度...", text: $naturalLanguageCommand, axis: .vertical)
                            .textFieldStyle(RoundedBorderTextFieldStyle())
                            .lineLimit(3...6)
                            .onSubmit {
                                processCommand()
                            }
                        
                        HStack {
                            Button(action: {
                                processCommand()
                            }) {
                                HStack {
                                    if isProcessing {
                                        ProgressView()
                                            .scaleEffect(0.8)
                                    } else {
                                        Image(systemName: "paperplane.fill")
                                    }
                                    Text(isProcessing ? "处理中..." : "发送")
                                }
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, 12)
                                .background(isProcessing ? Color.gray : Color.blue)
                                .foregroundColor(.white)
                                .cornerRadius(8)
                            }
                            .disabled(isProcessing || naturalLanguageCommand.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
                            
                            Button(action: {
                                naturalLanguageCommand = ""
                            }) {
                                Image(systemName: "xmark.circle.fill")
                                    .font(.title2)
                                    .foregroundColor(.red)
                            }
                            .disabled(naturalLanguageCommand.isEmpty)
                        }
                    }
                }
                .padding(.horizontal)
                
                // 常用命令建议
                VStack(alignment: .leading, spacing: 12) {
                    Text("常用指令")
                        .font(.headline)
                    
                    LazyVGrid(columns: [
                        GridItem(.flexible()),
                        GridItem(.flexible())
                    ], spacing: 8) {
                        ForEach(commonCommands, id: \.self) { command in
                            Button(action: {
                                naturalLanguageCommand = command
                                processCommand()
                            }) {
                                Text(command)
                                    .font(.caption)
                                    .padding(.horizontal, 12)
                                    .padding(.vertical, 8)
                                    .background(Color.blue.opacity(0.1))
                                    .foregroundColor(.blue)
                                    .cornerRadius(16)
                            }
                            .disabled(isProcessing)
                        }
                    }
                }
                .padding(.horizontal)
                
                // 执行状态
                if commandExecutor.isExecuting || isProcessing {
                    ExecutionStatusView(commandExecutor: commandExecutor, isProcessing: isProcessing)
                        .padding(.horizontal)
                }
                
                // 执行控制按钮
                if commandExecutor.isExecuting || isProcessing {
                    ExecutionControlView(
                        commandExecutor: commandExecutor, 
                        isProcessing: isProcessing,
                        onStopProcessing: {
                            // 中断AI处理过程
                            aiService.cancelProcessing()
                            isProcessing = false
                            naturalLanguageCommand = ""
                        }
                    )
                    .padding(.horizontal)
                }
                
                Spacer(minLength: 100)
            }
            .padding(.vertical)
        }
        .onTapGesture {
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
        }
        .onAppear {
            setupCommandExecutor()
            setupServices()
        }
        .alert("错误", isPresented: $showErrorAlert) {
            Button("确定") { }
        } message: {
            Text(errorMessage)
        }
        .alert("成功", isPresented: $showSuccessAlert) {
            Button("确定") { }
        } message: {
            Text(successMessage)
        }
    }
    
    // MARK: - 私有方法
    private func setupCommandExecutor() {
        // 设置命令执行器的回调
        commandExecutor.onCommandComplete = { index, command in
            print("命令 \(index + 1) 开始执行: \(command.direction.rawValue)")
        }
        
        commandExecutor.onExecutionComplete = {
            DispatchQueue.main.async {
                showSuccessAlert = true
                successMessage = "所有命令执行完成！"
                print("AI命令执行完成")
                // 重置所有状态
                isProcessing = false
                naturalLanguageCommand = ""
            }
        }
        
        commandExecutor.onExecutionError = { error in
            DispatchQueue.main.async {
                showErrorAlert = true
                errorMessage = error
                print("AI命令执行错误: \(error)")
                // 发生错误时也要重置状态
                isProcessing = false
            }
        }
    }
    
    private func processCommand() {
        let command = naturalLanguageCommand.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !command.isEmpty else { return }
        
        isProcessing = true
        
        // 首先检查是否为预定义命令
        if aiService.isPredefinedCommand(command) {
            if let predefinedCommands = aiService.getPredefinedCommands(command) {
                executeCommands(predefinedCommands, description: "执行预定义命令: \(command)")
                return
            }
        }
        
        // 使用AI服务处理自然语言命令
        aiService.processNaturalLanguageCommand(command) { result in
            DispatchQueue.main.async {
                isProcessing = false
                
                if result.success {
                    executeCommands(result.commands, description: result.message)
                } else {
                    showErrorAlert = true
                    errorMessage = result.error ?? "处理命令失败"
                }
            }
        }
    }
    
    private func executeCommands(_ commands: [CarControlCommand], description: String) {
        print("开始执行AI命令: \(description)")
        print("命令数量: \(commands.count)")
        
        for (index, command) in commands.enumerated() {
            print("命令 \(index + 1): \(command.direction.rawValue) \(command.speed.description) 持续时间: \(command.duration ?? 0)秒")
        }
        
        commandExecutor.executeCommands(commands)
    }
}

// MARK: - 子视图
struct ConnectionStatusView: View {
    @EnvironmentObject var tcpCarService: TCPCarService
    
    var body: some View {
        HStack {
            Circle()
                .fill(tcpCarService.isConnected ? Color.green : Color.red)
                .frame(width: 8, height: 8)
            
            Text(tcpCarService.isConnected ? "已连接" : "未连接")
                .font(.caption)
                .foregroundColor(tcpCarService.isConnected ? .green : .red)
            
            Spacer()
        }
        .padding(.vertical, 8)
        .padding(.horizontal, 12)
        .background(Color(.systemGray6))
        .cornerRadius(8)
    }
}

struct ExecutionStatusView: View {
    @ObservedObject var commandExecutor: AICommandExecutor
    let isProcessing: Bool
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("执行状态")
                .font(.headline)
            
            VStack(spacing: 8) {
                if isProcessing {
                    // AI处理中的状态
                    HStack {
                        ProgressView()
                            .scaleEffect(0.8)
                        Text("AI正在理解指令...")
                            .font(.caption)
                            .foregroundColor(.secondary)
                        Spacer()
                    }
                } else {
                    // 命令执行中的状态
                    ProgressView(value: commandExecutor.executionProgress)
                        .progressViewStyle(LinearProgressViewStyle())
                    
                    HStack {
                        Text(commandExecutor.executionStatus)
                            .font(.caption)
                            .foregroundColor(.secondary)
                        
                        Spacer()
                        
                        Text("\(commandExecutor.currentCommandIndex + 1)/\(commandExecutor.totalCommands)")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                    
                    if commandExecutor.remainingCommands > 0 {
                        Text("剩余 \(commandExecutor.remainingCommands) 个命令")
                            .font(.caption)
                            .foregroundColor(.blue)
                    }
                }
            }
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(12)
    }
}

struct ExecutionControlView: View {
    @ObservedObject var commandExecutor: AICommandExecutor
    let isProcessing: Bool
    let onStopProcessing: () -> Void
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("执行控制")
                .font(.headline)
            
            HStack(spacing: 12) {
                // 停止按钮 - 处理中和执行中都显示
                Button(action: {
                    if isProcessing {
                        onStopProcessing()
                    } else {
                        commandExecutor.stopExecution()
                    }
                }) {
                    HStack {
                        Image(systemName: "stop.fill")
                        Text(isProcessing ? "中断" : "停止")
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 12)
                    .background(Color.red)
                    .foregroundColor(.white)
                    .cornerRadius(8)
                }
                
                // 暂停和继续按钮只在命令执行中显示
                if !isProcessing {
                    if commandExecutor.canPause {
                        Button(action: {
                            commandExecutor.pauseExecution()
                        }) {
                            HStack {
                                Image(systemName: "pause.fill")
                                Text("暂停")
                            }
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 12)
                            .background(Color.orange)
                            .foregroundColor(.white)
                            .cornerRadius(8)
                        }
                    }
                    
                    if commandExecutor.canResume {
                        Button(action: {
                            commandExecutor.resumeExecution()
                        }) {
                            HStack {
                                Image(systemName: "play.fill")
                                Text("继续")
                            }
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 12)
                            .background(Color.green)
                            .foregroundColor(.white)
                            .cornerRadius(8)
                        }
                    }
                }
            }
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(12)
    }
}

// MARK: - 预览
struct AIControlView_Previews: PreviewProvider {
    static var previews: some View {
        AIControlView()
            .environmentObject(TCPCarService())
            .environmentObject(ConnectionSettings())
    }
} 